require(["jquery","template","bootstrap","echarts","bbcare",
	"scprit/department/view/template/follow-up/common.js",
	"oms_config/root"
],function($,template,bootstrap,echarts,$bb,$common,$root) {
	var URL = $bb.baseUrl("department")+"followup/service";
	var obj=$bb.getPageParams();
	var userId =obj.babyId ,type=obj.type;//历史记录传参
	var arr = new Array(), allPostion, monthAge=0, typeVal=0, gtype='A',monthType;
	$common.date();
	var account=eval('('+sessionStorage.account+')');
	var accountName=account.alias;
	getBabyInfo();
	getAllPostion();
	function getBabyInfo() {
		var config = $root.init();
		var showFlag = config.dom.baileyScreeningResultShowInfo ? "1" : "0";
		$bb.ajax({
			url: URL+"/patient/patientInfoPtId",
			data: JSON.stringify({
				data: {
					"patientId":userId,
					'showFlag':showFlag
				}
			}),
			success: function (data) {
				if(data.success) {
					for(var item in data.data){
						data.data.PatientInfo[item] = data.data[item];
					}
					var babyInfo=data.data.PatientInfo;
					var babyData=$common.babyInfoDeal(babyInfo);
					monthAge=babyData.monthAge;
					$common.infoInitNew({"id":"#babyInfoList","data":babyData});
					$("#nowTime").html($common.getNowFormatDate());
					$("#userName").html(accountName);//检查医生名字
				}
			}
		});
	}
	var bailyHistory = function(){
		$bb.openPage("baileyScreeningResult",obj);
	}
	var topbars = [
		{
			"icon":"fa fa-history",
			"name":"历史记录",
			"callback":bailyHistory
		}
	];
	$bb.toolbar(topbars);
	$("#submitData").click(function () {
		if(!$.isEmptyObject(arr)){
			$bb.ajax({
				url: URL+"/patient/evaluation/getScore",
				data: JSON.stringify({
					data: {
						"userId" : userId,
						"examinationPaperName" : type,
						"postionIds" : JSON.stringify(arr)
					}
				}),
				success: function (data) {
					if(data.success) {
						obj.result=data.data;
						$bb.openPage("baileyScreeningResult",obj);
					}
				}
			});
		}else{
			$bb.toastShow("您的量表还没有做哦，请做完之后再提交！");
		}
	});
	(function() {
		qustions = function(node, postions,fld) {
			this.containerNode = node;
			this.orgData = postions;//s数据源
			this.showNumber = postions.length; //每组显示X条数据
			this.groupIndex = 0;  //当前租索引
			this.groupName = fld;
			this.initQuestionsStyle();  //初始化样式
		};
		qustions.prototype.initQuestionsStyle = function(itemIndex){
			var _this = this, data = _this.orgData, showNumber = _this.showNumber, count = data.length,
				groupIndex = _this.groupIndex,groupName= _this.groupName, start = 0, end = 0, str = '</li>';
			start = groupIndex * showNumber;
			end = (groupIndex + 1) * showNumber;
			end > count?(end = count):'';
			for(var i=start; i< end; i++){
				var cls  = ' class=';
				if(i == start || i == itemIndex) cls += '"select" ';
				str += '<li tp="slect" itemIndex="'+ i +'"  id="'+data[i].id+'" style="cursor:pointer;">'+ data[i].name +'</li>';
			}
			str += '</li>';

			_this.containerNode.html(str);
			setStyle();                 //初始化题目选中状态
			_this.bind(groupName);               //绑定题目和上一组下一组的单击事件
		};
		qustions.prototype.bind = function(groupName) {
			var _this = this;
			_this.containerNode.find("li[tp=slect]").click(function() {
				var id = $(this).attr("id");
				var start= group(allPostion, groupName[0], gtype)[0];
				if($(this).hasClass("select")){
					if(!isSelectStart(groupName[0], id)) {
						if(confirm("您取消了宝宝月龄段起点,之后的选中项都会被。是否确认清除？")){
							cancelAllByStartAfter(groupName[0], id);
							$(this).removeClass("select");
						}
					} else if(cancelByGroup(groupName[0],id)){
						if(confirm("连续4项(包括前一段)中没有一项通过,之后的选中项都会被。是否确认清除？")){
							cancelAllByStartAfter(groupName[0], id);
							$(this).removeClass("select");
						} else {
							arr.push(id);
							$(this).addClass("select");
						}
					} else {
						$common.removeByValue(arr,$(this).attr("id"));
						$(this).removeClass("select");
					}
				} else {
					var groupA = group(allPostion, groupName[0], "A")[0];
					if(id*1.0 == start*1.0 || isSelectStart(groupName[0]) || id*1.0 == groupA*1.0) {
						if(isStartBefore(groupName[0], id)) {
							if(id*1.0 == start*1.0 && !isSelectByStartBefore(groupName[0])) {
								selectAllByStartBefore(groupName[0]);
							} else {
								if(isValueByArr(groupName[0], id)) {
									alert("之前连续4项(包括前一段)中有一项通过才可通过此项！");
								}else {
									if(!$common.contains(arr, id+"")) {
										arr.push(id);
										$(this).addClass("select");
									}
								}
							}
						} else {
							if(isSelectStart(groupName[0]) || isStartSelect(groupName[0])) {
								if(isValueByArr(groupName[0], id)) {
									alert("之前连续4项(包括前一段)中有一项通过才可通过此项！");
								}else {
									if(!$common.contains(arr, id+"")) {
										arr.push(id);
										$(this).addClass("select");
									}
								}
							} else {
								alert("宝宝对应月龄段段第一项必须通过才可通过此项！");
							}
						}
					} else {
						alert("宝宝起始项必须通过才可通过此项！");
					}
				}
			});
		};
		qustions.prototype.selectItemBefore = function(e){
			var _this = this, $node = $(e), data = _this.orgData, itemIndex = (parseInt($node.attr("itemIndex")) + 1);
			var _ul = $(e).parent().children().first();
			if(typeof(_ul.attr("id")) == "undefined"){
				$(e).prevAll(":not(:last)").addClass("select");
			} else {
				$(e).prevAll().addClass("select");
			}
			for(var i=0; i< itemIndex; i ++){  //更新选中arr数组
				var id = data[i].id;
				if($.inArray(id, arr) < 0){
					if(!$common.contains(arr, id+"")) arr.push(id);
				}
			}
		}
	})();
	function getAllPostion() {
		$bb.ajax({
			url: URL+"/patient/evaluation/getAllPostion",
			data: JSON.stringify({
				data: {
					"examinationPaperName" : type,//评测类型；
					"userId":userId
				}
			}),
			success: function (data) {
				if (data.success) {
					allPostion = data.data;
					$.tabs = {
						init: function (papers) {
							data = {
								tabs: {
									cognitive: "认知能力",
									understand: "语言理解",
									express: "语言表达",
									fineMotor: "精细运动",
									bigAction: "大动作"
								},
								selectItem: {
									A: '0-6月龄',
									B: '7~12月龄',
									C: '13~24月龄',
									D: '25~42月龄'
								},
								src:{
									cognitive: "page/department/img/notice.png",
									understand: "page/department/img/text.png",
									express: "page/department/img/say.png",
									fineMotor: "page/department/img/sportsmin.png",
									bigAction: "page/department/img/bigSports.png"
								},
								data: papers
							};
							this.orgData = data;
							this.initTabsStyle();
						},
						bind: function () {
							var _this = this, data = _this.orgData, tabs = data.tabs, question = data.data,selectItem=data.selectItem;
							$(".line>div").click(function () {
								var fld = $(this).attr("barField").split("."),
									index=$(this).index();
									qustionsData = question[fld[0]][fld[1]],
								$(this).siblings().removeClass('selected-fu').find("span").removeClass("selected");
								$(this).addClass('selected-fu').find("span").addClass("selected");
								new qustions($(this).parents("li").find(".classification"), qustionsData, fld);
								var height=$(this).parents("#allQuestion li").height();
								$(this).parents("#allQuestion li").find("div[class='leftTitle']").css("height",height+"px");
								if(index=="0"){
									$(this).parents("#allQuestion li").find(".month").html(selectItem.A);
								}else if(index=="1"){
									$(this).parents("#allQuestion li").find(".month").html(selectItem.B);
								}else if(index=="2"){
									$(this).parents("#allQuestion li").find(".month").html(selectItem.C);
								}else if(index=="3"){
									$(this).parents("#allQuestion li").find(".month").html(selectItem.D);
								}
							});
							$(".line").each(function () {
								if (0 < monthAge && monthAge <= 7) {
									$(this).find("div[barField]:eq(0)").click();
									typeVal = 1;
									gtype = 'A';
								}
								if (7 < monthAge && monthAge <= 13) {
									$(this).find("div[barField]:eq(1)").click();
									typeVal = 2;
									gtype = 'B';
								}
								if (13 < monthAge && monthAge <= 25) {
									$(this).find("div[barField]:eq(2)").click();
									typeVal = 3;
									gtype = 'C';
								}
								if (25 < monthAge && monthAge <= 42) {
									$(this).find("div[barField]:eq(3)").click();
									typeVal = 4;
									gtype = 'D';
								}
							});
						},
						initTabsStyle: function () {
							var _this = this, data = _this.orgData, tabs = data.tabs, question = data.data,src=data.src,
								selectItem = data.selectItem, htmlTab = '';
							if (0 <= monthAge && monthAge <= 7) {
								$(this).find("li[barField]:eq(0)").click();
								monthType="0-6月";
							}
							if (7 < monthAge && monthAge <= 13) {
								$(this).find("li[barField]:eq(1)").click();
								monthType="7-12月";
							}
							if (13 < monthAge && monthAge <= 25) {
								$(this).find("li[barField]:eq(2)").click();
								monthType="13-24月";
							}
							if (25 < monthAge && monthAge <= 42) {
								$(this).find("li[barField]:eq(3)").click();
								monthType="25-42月";
							}
							$.each(question, function (filed, itemQ) { //解析tabs字段
								if (typeof(tabs[filed]) == "undefined") {
									return true;
								}
								var barTab = '', indexBar = 0, classBar = '';
								$.each(itemQ, function (selectName, itemB) {

									if (indexBar == 0) {  //默认选中第一个
										classBar = "secondC different";
									} else {
										classBar = "";
									}
									barTab += '<div barField="' + filed + '.' + selectName + '">' + selectName + '段<span></span></div>';
									indexBar++;// 索引自增
								});
								htmlTab += '<li>'+
												'<div class="leftTitle">'+
													'<div class="left-pos"><div class="img">'+
														'<img src="'+src[filed]+'" alt=""/>'+
														'</div>'+
														'<font>'+tabs[filed]+'</font><br/>'+
														'<font class="month">'+monthType+'</font>'+
												'</div></div>'+
												'<div class="rightContent">'+
													'<ul class="classification">'+'</ul>'+
													'<div class="line" >'+barTab+
													'</div>'+
												'</div>'+
										'</li>'
							});
							$("#allQuestion").html(htmlTab);
							_this.bind();
						}

					};
					$.tabs.init(data.data); //初始化数据
					$("#submitData").removeAttr("disabled");
				}
			}
		});
	}
	$(window).resize(function(){
		for(var i=0;i<$("#allQuestion>li").length;i++){
			var height=$("#allQuestion>li").eq(i).height();
			$("#allQuestion>li").eq(i).find("div[class='leftTitle']").css("height",height+"px");
		}
	});
	function setStyle() {
		for(var i=0;i<arr.length;i++){
			$("#"+arr[i]).addClass("select");
		}
	}
	 //前4项是否被选中
	 //group：包含该组所有题目的数组
	 //val：	值
	 function isValueByArr(groupName, val) {
		 var position =0;
		 var allGroup = getGroupByName(groupName);
		 for(var i=0; i<allGroup.length; i++) {
			 if(allGroup[i] == val) {
			 position = i;
			 break;
			 }
		 }
		 if(position>3) {
			 if(!$common.contains(arr, allGroup[position-1]+"") && !$common.contains(arr, allGroup[position-2]+"") &&
			 !$common.contains(arr, allGroup[position-3]+"")&& !$common.contains(arr, allGroup[position-4]+"")) {
			 return true;
		 	}
		 }
		 return false;
	 }

	 //取消月龄段起点之后
	 function cancelAllByStartAfter(groupName, index) {
		 var allGroup = getGroupByName(groupName);
		 for(var i=0; i<allGroup.length; i++) {
			 if(allGroup[i]*1.0 >= index*1.0) {
				 if($common.contains(arr, allGroup[i]+"")) {
					 $common.removeByValue(arr,allGroup[i]);
					 $("#"+allGroup[i]).removeClass("select");
				 }
			 }
		 }
	 }

	 function isSelectStart(groupName, id) {
		 $common.removeByValue(arr,id);
		 var groupA = group(allPostion, groupName, "A")[0];
		 if($common.contains(arr, groupA+"")) return true;
		 return false;
	 }

	 //取消后是否有4个未选中
	 //project: 项目
	 //id：当前按钮
	 function cancelByGroup(project, id) {
		 $common.removeByValue(arr,id);
		 $("#"+id).removeClass("select");
		 var num = 0,temp=0, postion;
		 var allGroup = getGroupByName(project);
		 for(var j=0;j<allGroup.length;j++){
		 	if($common.contains(arr, allGroup[j]+"")) postion = allGroup[j];
	 	}

		 for(var i=0;i<allGroup.length;i++) {
			 if(allGroup[i]*1.0<postion*1.0) {
				 console.info(allGroup[i]+"   "+$common.contains(arr, allGroup[i]+""));
				 if($common.contains(arr, allGroup[i]+"")) {
					num = 0;
				 }else {
					num++;
				 }
				if(num>3) return true;
			 }
		 }
		 return false;
	 }

	 //选中月龄段起点之前
	 function selectAllByStartBefore(groupName) {
		 var startIndex = group(allPostion, groupName, gtype)[0];
		 var allGroup = getGroupByName(groupName);
		 for(var i=0; i<allGroup.length; i++) {
			 if(allGroup[i]*1.0 <= startIndex*1.0) {
				 if(!$common.contains(arr, allGroup[i]+"")) {
					 arr.push(allGroup[i]);1
					 $("#"+allGroup[i]).addClass("select");
				 }
			 }
		 }
	 }

	 //月龄段第一项之前是否有被选中的
	 function isSelectByStartBefore(groupName) {
		 var startIndex = group(allPostion, groupName, gtype)[0];
		 var allGroup = getGroupByName(groupName);
		 for(var i=0; i<allGroup.length; i++) {
			 if(allGroup[i]*1.0 < startIndex*1.0) {
			 	if($common.contains(arr, allGroup[i]+"")) {return true;}
			 }
		 }
		 return false;
	 }

	 //月龄段第一项是否被选中
	 function isStartSelect(groupName) {
		 var startIndex = group(allPostion, groupName, gtype)[0];
		 if($common.contains(arr, startIndex+"")) return true;
		 return false;
	 }
	 //获取点击按钮在 宝宝对应月龄起点之前还是之后(true-前，false-后)
	 function isStartBefore(groupName, id) {
		 var startIndex = group(allPostion, groupName, gtype)[0];
		 if(startIndex*1.0 < id*1.0) return false;
		 return true;
	 }

	 //根据组名获取该组所有项目
	 function getGroupByName(groupName) {
		 var a = group(allPostion, groupName, "A");
		 var b = group(allPostion, groupName, "B");
		 var c = group(allPostion, groupName, "C");
		 var d = group(allPostion, groupName, "D");

		 var groupAll = a.concat(b).concat(c).concat(d);
		 return groupAll;
	 }

	 //获取某个能区中某个年龄段的题目ID数组
	 //data：后台传递来的数据
	 //type：某个能区
	 //action： 某个年龄段
	 function group(data ,type, action) {
	 	return data[type][action].map(function(item) {return item.id});
	 }
});